package cn.school.demo.ui.history

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.school.demo.MyApplication
import cn.school.demo.pojo.ArticleBrowse
import cn.school.demo.pojo.Browse
import cn.school.demo.repository.HistoryRepository
import com.blankj.utilcode.util.LogUtils

class HistoryViewModel : ViewModel() {

    private val _tabTitle: MutableList<String> = mutableListOf("文章历史", "答题历史")
    val tabTitle: MutableList<String>
        get() = _tabTitle

    private var _browseHistory =
        HistoryRepository().getUserBrowseInfo(MyApplication.user!!.sfNumber)
    val browser: LiveData<MutableList<ArticleBrowse>> get() = _browseHistory

    private val _choose = MutableLiveData<MutableList<Int>>(mutableListOf())
    val choose: LiveData<MutableList<Int>> get() = _choose

    private lateinit var _result: LiveData<Boolean>
    val result: LiveData<Boolean> get() = _result

    fun addChoose(id: Int) {
        val l: MutableList<Int> = _choose.value!!
        l.add(id)
        _choose.value = l
    }

    fun removeChoose(id: Int) {
        val l: MutableList<Int> = _choose.value!!
        l.remove(id)
        _choose.value = l
    }

    fun clearChoose() {
        val l: MutableList<Int> = _choose.value!!
        l.clear()
        _choose.value = l
    }

    fun delete(isAll: Boolean) {
        LogUtils.d(_choose.value.toString())
        val deleteList = mutableListOf<Browse>()
        if (!isAll) {
            _choose.value?.let {
                if (_choose.value!!.isNotEmpty()) {
                    _choose.value!!.forEach {
                        deleteList.add(
                            Browse(
                                MyApplication.user!!.sfNumber,
                                _browseHistory.value!![it].article!!.articleId,
                                _browseHistory.value!![it].time.browseTime
                            )
                        )
                    }
                }
            }
        } else {
            _browseHistory.value?.forEach {
                if (it.article != null) {
                    deleteList.add(
                        Browse(
                            MyApplication.user!!.sfNumber,
                            it.article!!.articleId,
                            it.time.browseTime
                        )
                    )
                }
            }
        }
        _result = HistoryRepository().deleteUserBrowseInfo(deleteList)
    }

    fun getBrowseHistory(): LiveData<MutableList<ArticleBrowse>> {
        return HistoryRepository().getUserBrowseInfo(MyApplication.user!!.sfNumber)
    }

    /*fun updateArticleHistory() {
        if (_choose.value!!.isNotEmpty()) {
            _choose.value!!.forEach { choose ->
                _browseHistory.value?.removeAt(choose) ?: LogUtils.e("系统出现严重错误！")
            }
        }
    }*/
}